package com.uam.core.dao.mysql;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.uam.core.entity.model.TaskStatModel;

import lombok.extern.slf4j.Slf4j;

@Repository
@Slf4j
public class TaskStatDao {

	@Autowired
	private JdbcTemplate jdbcTemplate = null;

	private boolean taskStatIsExist(int status) {
		return this.jdbcTemplate.query(con -> {
			PreparedStatement ps = con.prepareStatement("SELECT `STATUS` FROM `TASK_STAT` WHERE `STATUS`=?");
			ps.setInt(1, status);
			return ps;
		}, new ResultSetExtractor<Boolean>() {
			public Boolean extractData(ResultSet resultSet) throws SQLException, DataAccessException {
				return Boolean.valueOf(resultSet.next());
			}
		}).booleanValue();
	}

	public boolean saveTaskStat(TaskStatModel taskStat) {
//		TaskStatDao.log.info("---------保存任务统计，params:{}---------", taskStat);
		int status = taskStat.getStatus();
		if (!this.taskStatIsExist(status)) {
			return this.jdbcTemplate.update(con -> {
				PreparedStatement ps = con
						.prepareStatement("INSERT INTO `TASK_STAT`(`STATUS`,`NUM`,`TIME`) VALUES (?,?,?)");
				ps.setInt(1, status);
				ps.setInt(2, taskStat.getNum());
				ps.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
				return ps;
			}) == 1;
		}
		return this.jdbcTemplate.update(con -> {
			PreparedStatement ps = con
					.prepareStatement("UPDATE `TASK_STAT` SET `NUM`=?,`TIME`=? WHERE `STATUS`=?");
			ps.setInt(1, taskStat.getNum());
			ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
			ps.setInt(3, status);
			return ps;
		}) == 1;
	}

	public void saveTaskStatNew() {
		this.jdbcTemplate.execute("UPDATE TASK_STAT set NUM=0, TIME=NOW(); INSERT INTO TASK_STAT (`STATUS`, NUM,TIME)\n" +
				"SELECT `STATUS`, `NUM`,TIME\n" +
				"FROM (\n" +
				"SELECT  `STATUS`, count(1) `NUM` , NOW() TIME from TASK where 1=1 and (`STATUS`=2 or `STATUS`=0 or `STATUS`=1 or `STATUS`=4 or `STATUS`=3 or `STATUS`=5 or `STATUS`=6) GROUP BY `STATUS`\n" +
				") a\n" +
				"ON DUPLICATE KEY UPDATE `STATUS` = VALUES(`STATUS`), NUM = VALUES(NUM), TIME=VALUES(TIME);");
	}

}
